<?php

/**
 * Created by PhpStorm.
 * User: steven
 * Date: 2016/4/20
 * Time: 22:59
 */
class JsapiTicketClass
{
    protected $CI;

    // We'll use a constructor, as you can't directly call a function
    // from a property definition.
    public function __construct()
    {
        // Assign the CodeIgniter super-object
        $this->CI =& get_instance();
        $this->CI->load->model('Jsapi_Ticket_Model');
        $this->CI->load->library('AccessTokenClass');
    }

    public function get_jsapi_ticket(){
        $jsapi_ticket=$this->get_jsapi_ticket_from_db();
        return $jsapi_ticket;
    }

    public function get_jsapi_ticket_from_db(){
        $jsapi_tickets=$this->CI->Jsapi_Ticket_Model->get_jsapi_ticket();
        if(empty($jsapi_tickets)||count($jsapi_tickets)==0){
        //    print_r("it's in insert section");
            $ticket=$this->get_new_jsapi_ticket();
            $data=array(
                'is_deleted'=>'N',
                'gmt_create'=>date("Y-m-d H:i:s" ,time()),
                'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
                'jsapi_ticket'=>$ticket,
                'expire_time'=>time()+7200
            );
            $this->CI->Jsapi_Ticket_Model->insert_jsapi_ticket($data);
            return $ticket;
        }else{
        //    print_r("it,s in reading ticket section");
            $jsapi_ticket_row=$jsapi_tickets;
        //    print_r($jsapi_ticket_row);
            $expire_time=$jsapi_ticket_row['expire_time'];
        //    print_r($expire_time);
            $jsapi_ticket=$jsapi_ticket_row['jsapi_ticket'];
        //    print_r('old ticket'.$jsapi_ticket);
            if(strtotime($expire_time)-200<time()){

                $jsapi_ticket1=$this->expire_jsapi_ticket($jsapi_ticket_row['id']);
                return $jsapi_ticket1;
            }else{
                return $jsapi_ticket;

            }
        }
    }

    public function expire_jsapi_ticket($id){
        $ticket=$this->get_new_jsapi_ticket();
       // print_r('new ticket is '.$ticket);
        $data=array(
            'id'=>$id,
            'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
            'jsapi_ticket'=>$ticket,
            'expire_time'=>date("Y-m-d H:i:s" ,time()+7200)
        );
    //    print_r($data);
        $this->CI->Jsapi_Ticket_Model->update_jsapi_ticket($data);
        return $ticket;
    }

    public function get_new_jsapi_ticket(){
        $access_token=$this->CI->accesstokenclass->get_access_token();
        $jsapi_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token ."&type=jsapi" ;
        $res = file_get_contents($jsapi_url); //获取文件内容或获取网络请求的内容
//echo $res;
    //    print_r($res);
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        $ticket = $result['ticket'];
        return $ticket;
    }
}